//
//  DXHomeViewController.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/5.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import SVProgressHUD
let KtopTipHeight:CGFloat = 35
let identifiterOfCell = "homeCell"
class DXHomeViewController: DXBaseTableViewController {
// 数据模型数组
//    var homeViewModel:DXHomeViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        判断是否登陆来显示主页界面
         isLogin ? setUpLoginView() : setUpOutView()
//        下载数据
          loadData()
    }
    
   
    // MARK: - 设置登陆界面逻辑
@objc private func setUpLoginView(){
    title = "首页"
    
    navigationItem.leftBarButtonItem = UIBarButtonItem.customItem( imgName: "navigationbar_friendsearch", target: self, action: "leftBarButtonItemClick")
    
    navigationItem.rightBarButtonItem = UIBarButtonItem.customItem( imgName: "navigationbar_pop", target: self, action: "rightBarButtonItemClick")
    
    
    
//MARK: 设置tableview的相关参数,约束
    tableView.registerClass(DXHomeTableViewCell.self, forCellReuseIdentifier: identifiterOfCell)
//    自动计算宽高
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 50
//    tableView的背景色
    tableView.backgroundColor = UIColor.whiteColor()
//    tableView的分隔线样式
    tableView.separatorStyle = .None
//    设置上拉刷新控件
//    MARK:refreshControl
    tableView.addSubview(freshControl)
    freshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//    添加提示控件
    navigationController?.view.insertSubview(topTipsLabel, belowSubview: navigationController!.navigationBar)
    
    
//    设置tableView的footerView
    let footerView = UIView(frame:CGRectMake(0, 0, 10, 30))
    tableView.tableFooterView = footerView
    footerView.addSubview(actIndicator)
    
//MARK:    约束布局
//     actIndicator约束
    actIndicator.snp_makeConstraints { (make) -> Void in
        make.centerY.equalTo(footerView)
        make.centerX.equalTo(footerView)
    }
//    topTipsLabel的约束
     topTipsLabel.snp_makeConstraints { (make) -> Void in
        make.size.equalTo(CGSizeMake(tableView.frame.width, KtopTipHeight))
        make.bottom.equalTo(navigationController!.navigationBar)
    }
    
}
    

// MARK:- 懒加载控件
//    上拉加载控件的菊花
    lazy var actIndicator:UIActivityIndicatorView = {
    let actIndicator = UIActivityIndicatorView()
        actIndicator.activityIndicatorViewStyle = .Gray
//        actIndicator.startAnimating()
    
    return actIndicator
    }()
    
    
    lazy var freshControl:DXRefreshControl = DXRefreshControl()
    lazy var topTipsLabel:UILabel = {
       let topTipsLabel = UILabel()
       topTipsLabel.font =  UIFont.systemFontOfSize(13)
       topTipsLabel.backgroundColor = UIColor.orangeColor()
        topTipsLabel.textAlignment = .Center
        topTipsLabel.textColor = UIColor.whiteColor()
        topTipsLabel.hidden = true
        return topTipsLabel
    }()
    
// MARK: - 下载数据  
  @objc  private func loadData(){
    
        //    下载首页数据
        DXHomeViewModel.shareHomeViewModel.loadHomeData (isPulling:actIndicator.isAnimating(),isUping:freshControl.isFreshing ) { (isSucess) -> () in
             self.actIndicator.stopAnimating()
            if isSucess {
                self.tableView .reloadData()
               
            }else{
//                网络异常提示
                SVProgressHUD.showErrorWithStatus("网络异常", maskType: .Black)
                
            }
//            提示加载数据数
            if self.freshControl.isFreshing {
                self.topTip()
            }
//            刷新控件停止刷新
            self.freshControl.endRefreshing()
        }
    }
    
    
    private func topTip(){
     self.topTipsLabel.hidden = false
    topTipsLabel.text = "加载了\(DXHomeViewModel.shareHomeViewModel.requestDataCount)条数据"
       
    UIView.animateWithDuration(0.25, animations: { () -> Void in
        self.topTipsLabel.transform = CGAffineTransformMakeTranslation(0, KtopTipHeight)
        }, completion: { (_) -> Void in
           UIView.animateWithDuration(0.25, delay: 1, options: [], animations: { () -> Void in
            self.topTipsLabel.transform = CGAffineTransformIdentity
            }, completion: { (_) -> Void in
                self.topTipsLabel.hidden = true
           })
        })
        
    }
    
}


// MARK: - 返回tabelView
extension DXHomeViewController{
//    返回行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return DXHomeViewModel.shareHomeViewModel.statuseList?.count ?? 0;
    }
//    返回怎么样的cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifiterOfCell, forIndexPath: indexPath)
        
      let homeCell = cell as! DXHomeTableViewCell
        
        let statuesViewModel = DXHomeViewModel.shareHomeViewModel.statuseList![indexPath.row]
        
        homeCell.statuesVeiwModel = statuesViewModel
        homeCell.selectionStyle = .None

        return homeCell
    }
    
//    将要显示cell的代理方法
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let statuseCount = DXHomeViewModel.shareHomeViewModel.statuseList!.count
        if indexPath.row == (statuseCount - 1) && !actIndicator.isAnimating(){
          actIndicator.startAnimating()
        loadData()
//        logPrint("最后:\(indexPath.row)")
            
        }
    }

}

// MARK: - 首页导航页的设置
extension DXHomeViewController{
    // 未登录的状态
    @objc private func setUpOutView(){
        
    }
    
    // MARK: - 主页leftBarBtton点击事件
    @objc private func leftBarButtonItemClick(){
        
        navigationController?.pushViewController(DXTempViewController(), animated: true)
        
    }
    // MARK: - 主页rightBarBtton点击事件
    @objc private func rightBarButtonItemClick(){
        
        navigationController?.pushViewController(DXTempViewController(), animated: true)
    }
}








